from bs4 import BeautifulSoup


class Twitter(object):

    def get_user_twitter(self,html):
        soup = BeautifulSoup(html, 'html.parser')
        # 博文主体模块
        divs = soup.find_all(
            'article', {'class': 'css-1dbjc4n r-1loqt21 r-18u37iz r-1ny4l3l r-1udh08x r-1qhn6m8 r-i023vh r-o7ynqc r-6416eg', 'data-testid': 'tweet'})
        nickname = soup.find('div',{'class','css-901oao r-1awozwy r-18jsvk2 r-6koalj r-37j5jr r-adyw6z r-1vr29t4 r-135wba7 r-bcqeeo r-1udh08x r-qvutc0'})
        if nickname is not None:
            nickname = nickname.get_text()
        
        user_twitters = {'nickname':nickname}
        user_twitters['articles'] = []
        for div in divs:
            article = {}
            #内容
            content = div.find('div',{'class':'css-901oao r-18jsvk2 r-37j5jr r-a023e6 r-16dba41 r-rjixqe r-bcqeeo r-bnwqim r-qvutc0'})
            if content is not None:
                content_text = str(content.get_text()).strip().replace('\n','')
                article['content'] = content_text
            else:
                content = div.find('div',{'class':'css-901oao r-18jsvk2 r-1tl8opc r-a023e6 r-16dba41 r-rjixqe r-bcqeeo r-bnwqim r-qvutc0'})
                if content is not None: 
                    content_text = str(content.get_text()).strip().replace('\n','')
                    article['content'] = content_text
                else:
                    article['content'] = 'None'
            
            #链接
            a = div.find('a',{'class':'css-4rbku5 css-18t94o4 css-901oao r-14j79pv r-1loqt21 r-1q142lx r-37j5jr r-a023e6 r-16dba41 r-rjixqe r-bcqeeo r-3s2u2q r-qvutc0'})
            if a is not None:
                link = 'https://twitter.com'+a['href']
                article['link']=link
            else:
                article['link']='None'
            #是否置顶
            has_top = div.find('div',{'class':'css-901oao css-cens5h r-14j79pv r-37j5jr r-n6v787 r-b88u0q r-1cwl3u0 r-bcqeeo r-qvutc0'})
            if has_top is not None:
                article['hasTop'] = True
            else:
                article['hasTop'] = False
            
            user_twitters['articles'].append(article)
        return user_twitters

    def get_user_name(self,uid):
        from utils.chrome_util import chrome
        url = 'https://twitter.com/'+uid
        html = chrome.get_twitter(url)
        twitters = self.get_user_twitter(html)
        nickname = twitters['nickname']
        return nickname

twitter = Twitter()